package com.youku.bootstrap;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.youku.util.Consts;
import com.youku.util.PropertyReader;

public class Bootstrap {

	private static final String DIR_KEY = "user.dir";

	private static final Logger logger = LoggerFactory.getLogger(Bootstrap.class);

	public static void main(String[] args) throws IOException {
		String command = Consts.REGULAR_COMMAND;
		switch (args.length) {
		case 0:
			break;
		case 1:
			command=args[0];
			break;
		default:
			throw new IllegalArgumentException("参数个数只能是0个或者1个。");
		}
		
		if(!PlatformExecutorHolder.isLegalCommand(command)){
			throw new IllegalArgumentException("请传入参数\n-r 定期执行项目\n-i 即时执行项目，只执行一次");
		}
		
		logger.info("项目执行命令为：{}",command);
		
		String dirPath = PropertyReader.read(Consts.TESTCASE_DIR);

		logger.info("获取到配置文件目录在{}路径下", dirPath);

		File dir = new File(dirPath);

		if (!dir.isDirectory()) {
			throw new IllegalArgumentException("参数应该是一个目录");
		}

		Scheduler scheduler = Scheduler.getInstance(command);
		File[] fileArr = dir.listFiles();
		for (File fileDir : fileArr) {
			if (fileDir.isDirectory()) {
				System.setProperty(DIR_KEY, fileDir.getCanonicalPath());
				for (String fileName : fileDir.list()) {
					if (isNotification(fileName)) {
						scheduler.buildNotifyDocument(fileName);
					} else if (isAutotest(fileName)) {
						scheduler.buildCoreDocument(fileName);
					}
				}
			}
		}

		scheduler.schedule();

	}

	private static boolean isAutotest(String fileName) {
		return StringUtils.equals(fileName, "autotest.xml");
	}

	private static boolean isNotification(String fileName) {
		return StringUtils.equals(fileName, "notification.xml");
	}
}
